package xyz.kongbai121.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import xyz.kongbai121.common.redis.serializer.DictInitCacheRunner;
import xyz.kongbai121.common.utils.PageUtils;
import xyz.kongbai121.common.utils.Query;
import xyz.kongbai121.modules.sys.dao.SysDictTypeDao;
import xyz.kongbai121.modules.sys.entity.SysDictTypeEntity;
import xyz.kongbai121.modules.sys.service.SysDictTypeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;


@Service("sysDictTypeService")
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeDao, SysDictTypeEntity> implements SysDictTypeService {

    @Autowired
    private DictInitCacheRunner cacheRunner;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysDictTypeEntity> page = this.page(
                new Query<SysDictTypeEntity>().getPage(params),
                getWrapper(params)
        );

        return new PageUtils(page);
    }

    private QueryWrapper<SysDictTypeEntity> getWrapper(Map<String, Object> params){
        String dictType = (String) params.get("dictType");
        String dictName = (String) params.get("dictName");

        QueryWrapper<SysDictTypeEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(dictType), "dict_type", dictType);
        wrapper.like(StringUtils.isNotBlank(dictName), "dict_name", dictName);
        wrapper.orderByDesc("sort", "create_time");

        return wrapper;
    }

    @Override
    public SysDictTypeEntity getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    public boolean save(SysDictTypeEntity entity) {
        //存Redis
        cacheRunner.setDictData(entity.getDictName());
        return super.save(entity);
    }

    @Override
    public boolean updateById(SysDictTypeEntity entity) {
        //Redis替换名称
        Optional.ofNullable(baseMapper.selectById(entity.getId())).ifPresent(dict -> {
            cacheRunner.renameIfAbsent(dict.getDictType(), entity.getDictType());
        });
        return super.updateById(entity);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        if (super.removeByIds(idList)) {
            cacheRunner.initDictData();
            return true;
        }
        return false;
    }

}